<?php
class System_View_Helper_Jstree extends ZendX_JQuery_View_Helper_UiWidget
{
    protected $_defaultOptions = array (
        'themes' => array(
            'theme' => 'default',
            'url' => '/style/jquery.jsTree/default/style.css'
        ),
        'ui' => array ( 'select_limit' => 1, ),
        'types' => array (
            'types' => array (
                'default' => array (
                    'icon' => array (
                        'image' => '/style/jquery.jsTree/images/file.png',
                    ),
                ),
                'folder' => array (
                    'icon' => array (
                        'image' => '/style/jquery.jsTree/images/folder.png',
                    ),
                ),
                'drive' => array (
                    'icon' => array (
                        'image' => '/style/jquery.jsTree/images/root.png',
                    ),
                ),
            ),
        ),
        'plugins' => array('json_data', 'themes', 'ui', 'types', 'cookie')
    );

    public function init($attrs, array $rows, $rootId = 0, $options = array())
    {
        if (is_string($attrs)) {
            $attrs = array('id' => $attrs);
        }
        if (!is_array($attrs) || empty($attrs['id'])) throw new IG_Exception('未设置属性 ID');

        $this->view->headScript()->appendFile('/scripts/jquery/jquery.jstree.js');
        $this->view->headScript()->appendFile('/scripts/jquery/jquery.cookie.js');

        $options['json_data'] = array('data' => $this->toJstreeData($rows, $rootId));

        $options = array_merge($options, $this->_defaultOptions);

        $js = sprintf('$("#%s").jstree(%s);', $attrs['id'], Zend_Json::encode($options));
        $this->jquery->addOnLoad($js);

        $html = '<div'
              . $this->_htmlAttribs($attrs)
              . '></div>';
        return $html;
    }

    public function jstree()
    {
        return $this;
    }

    public function toJstreeData($rows, $rootId, $toJson = false)
    {
        $data = array($rootId => array('children' => array()));
        foreach ($rows as $row) {
            $data[$row['id']] = (isset($data[$row['id']]) ?  $data[$row['id']] : array())
                              + array(
                'data' => array(
                    'title' => $row['title'],
                    'attr' => array(
                        'href'  => $row['url'],
                    ),
                ),
                'metadata' => $row,
                'attr' => array(
                    'id'   => 'ig-jstree-' . $row['id'],
                    'rel'  => $row['type'],
                ),
            );
            $data[$row['parent_id']]['children'][] = & $data[$row['id']];
        }
        if ($toJson) {
            return Zend_Json::encode($data[$rootId]['children']);
        } else {
            return $data[$rootId]['children'];
        }
    }
}